var path          = require('path');
global.prefixPath = path.resolve(__dirname);
var express       = require('express');
var responseTime  = require('response-time');
var favicon       = require('serve-favicon');
var logger        = require('morgan');
var cookieParser  = require('cookie-parser');
var bodyParser    = require('body-parser');
var cors = require('cors');   

//配置操作日志11
var log4js = require(process.cwd() + "/utils/log");
log4js.configure();

var applogger = log4js.logger("app");
var session   = require('express-session');
var url       = require('url');
var app       = express();
// var env       = require("./src/utils/env");
//配置文件
var config    = require('./config/config');
// var nowenv    = env.getEnv();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public dd dd
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.json({
    limit: "50mb"
}));
app.use(bodyParser.urlencoded({
    extended: false,
    limit   : '50mb'
}));

app.use(cookieParser());
app.use(config._config.rootPath, express.static(path.join(__dirname, 'public')));

app.use(responseTime(function (req, res, time) {
    var stat = (req.method + req.url).toLowerCase()
        .replace(/[:.]/g, '')
        .replace(/\//g, '_')
    applogger.info("cgi stat", stat, time);
    // log4js.setUserName("");
}))

//所有请求的入口
// app.use('/', routes);
app.use("/", function (req, res, next) {
    //先保存Hostname
    global.originalHost = req.protocol + "://" + req.headers.host;
    global.originalUrl  = req.url;

    // 跨域支持
    // res.header("Access-Control-Allow-Origin", "*");

    //所有动态请求的入口
    /*
     做了简单的改造，可以匹配/action,method然后调用对应的模块暴露出来的接口
     */
    var reg      = new RegExp("^" + config._config.rootPath);
    var reqRoute = path.normalize(process.cwd() + "/routes" + req.url.replace(/\//g, "/").replace(reg, "").replace(/\?.*/, ""));
    // console.log(reqRoute);
    var _reqArr  = reqRoute.split(/[,-]/);
    reqRoute     = _reqArr.length > 1 ? _reqArr[0] : reqRoute;
    var method   = _reqArr.length > 1 ? _reqArr[1] : "init";

    try {
        //先去尝试是否有对应的routes
        var appModule = require(reqRoute);
        appModule[method](req, res, next);
    } catch (e) {
        if (e.message == "Cannot find module '" + reqRoute + "'") {
            next();
        } else {
            //如果是模块里面出错，则直接打出出错信息
            res.render("error", {
                message: e.message,
                error  : e
            });
        }
    }

});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err    = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        global.renderError(res, err);
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error  : {}
    });
});

/**
 * 渲染错误页面
 * @author huangshaolu
 * @date   2016-03-03
 * @param  {Object}   res 回复
 * @param  {Object}   err 错误信息
 */
global.renderError = function (res, err) {
    res.render('error', {
        message: err.message,
        error  : err
    });
}

// 全局缓存机制
global._Cache = {
    data: {},
    get: function (name) {
        return this.data[name] && this.data[name].value;
    },
    set: function (name, value, time) {
        var that = this;
        // 如果存在
        if (this.data[name] && this.data[name].expires) {
            clearTimeout(this.data[name].expires);
            this.data[name].expires = null;
            delete this.data[name];
        }

        // 之后肯定是不存在了
        this.data[name] = {
            value: value
        };
        // 默认一个小时有效期
        this.data[name].expires = setTimeout(function () {
            delete that.data[name];
        }, time ? time : 10 * 60 * 1000);
    }
}

module.exports = app;